import { Subject } from 'rxjs';
import { Injectable } from '@angular/core';
import { DataChangeLog } from '../models/dataChangeLog';
import { BaseService } from './base.service';

@Injectable({
  providedIn: 'root'
})
export class DataChangeLogService extends BaseService {
  dataChangeLogUpdated$ = new Subject();
  dataChangeLogCountChanged$ = new Subject<number>();

  createDataChangeLog(data: DataChangeLog) {
    const url = `api/dataChangeLog`;
    return this.post(url, data);
  }

  queryDataChangeLog(params): Promise<DataChangeLog[]> {
    const url = `api/dataChangeLog`;
    return this.get(url, { params });
  }

  updataDataChangeLogStatus(id: string, status: string) {
    const url = `api/dataChangeLog/${id}/status/${status}`;
    return this.put(url, {});
  }

  async getMergedDataChangeLog(dataRegisterId: string): Promise<DataChangeLog> {
    const dataChangLogs = await this.queryDataChangeLog({ dataRegisterId, status: 'pass' });
    let result: DataChangeLog;

    if (dataChangLogs.length > 0) {
      result = dataChangLogs[0];
    }

    for (let i = 1; i < dataChangLogs.length; i++) {
      let item = dataChangLogs[i];
      for (let key in item.data) {
        if (key == 'createTime') {
          continue;
        }
        if (!result.data[key]) {
          result.data[key] = item.data[key];
        }
      }
    }

    return result;
  }
}
